<?php


namespace app\installs;


use app\helpers\AppHelper;
use app\helpers\EncryptHelper;
use app\models\Admin;
use app\models\User;
use Exception;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Migration;
use yii\helpers\Console;

class BaseInstall extends Migration {

    protected $postTable = '{{%post}}';
    protected $userTable = '{{%user}}';
    protected $metaTable = '{{%meta}}';
    protected $relationshipTable = '{{%relationship}}';
    protected $settingTable = '{{%setting}}';
    protected $commentTable = '{{%comment}}';

    protected $tableOptions = 'CHARACTER SET utf8 ENGINE=MyISAM';

    public function init() {
    }

    public function run($params) {
        try {
            $this->connection($params['db']);
//            $this->down();
            $this->up();
            $this->init_local_file($params['env']);
            $this->settingAdmin($params['user']);
            $this->init_db_file($params['db']);
            return AppHelper::success(null, 'Successful installation.');
        } catch (Exception $e) {
            return AppHelper::error($e->getMessage(), AppHelper::ERROR_CODE, [$e->getFile(), $e->getLine()]);
        }
    }

    /**
     * @param $params
     * @throws \yii\db\Exception
     */
    protected function settingAdmin($params) {
        self::stdout('[+]: Setting up Administrator Account.', Console::FG_GREEN);
        $model = new Admin();
        $model->setAttributes($params);
        $model->gid = Admin::GROUP_ADMIN;
        $model->status = Admin::YES;
        $model->nickname = $model->username;
        $model->password = EncryptHelper::md5($model->password);
        $model->save();
        self::stdout("APP_KEY: " . APP_KEY);
        self::stdout("管理员账号: {$model->username}");
        self::stdout("管理员密码: {$params['password']}");
    }

    /**
     * @param $params
     * @throws InvalidConfigException
     */
    protected function connection($params) {
        $data = [
            'class' => 'yii\db\Connection',
            'dsn' => "mysql:host={$params['db_host']};port={$params['db_port']};dbname={$params['db_name']}",
            'username' => $params['db_user'],
            'password' => $params['db_pass'],
            'charset' => 'utf8mb4',
            'tablePrefix' => $params['db_prefix']
        ];
        Yii::$app->set('db', $data);
        parent::init();
    }

    protected function init_db_file($params) {
        $db_file = SYS_ROOT . '/config/db.php';
        $string = <<<EOF
<?php    
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host={$params["db_host"]};port={$params["db_port"]};dbname={$params["db_name"]}',
    'username' => '{$params["db_user"]}',
    'password' => '{$params["db_pass"]}',
    'charset' => 'utf8mb4',
    'tablePrefix' => '{$params["db_prefix"]}',
    'enableSchemaCache' => true,
    'schemaCacheDuration' => 86400,
    'schemaCache' => 'cache_db_schema'
];
EOF;
        return file_put_contents($db_file, $string);
    }

    protected function init_local_file($app_env) {
        $key = strtoupper(md5(uniqid(mt_rand(10000, 99999))));
        defined('APP_KEY') or define('APP_KEY', $key);
        $local_file = SYS_ROOT . '/config/local.php';
        $string = "<?php\n";
        $string .= "defined('APP_KEY') or define('APP_KEY', '{$key}');\n";
        $string .= "defined('YII_ENV') or define('YII_ENV', '{$app_env}');\n";
        $string .= "defined('YII_DEBUG') or define('YII_DEBUG', YII_ENV !== 'prod');\n";
        return file_put_contents($local_file, $string);
    }

    protected static function stdout($string, $color = Console::FG_GREY) {
        $string = Console::ansiFormat("{$string}\n", [$color]);
        return Console::stdout($string);
    }
}